-module(send_msg).
-author("hpj").

-import(proplists, [get_value/2, get_value/3]).

-include("emqttd.hrl").

-include("mysql.hrl").

%% API
-export([handle/1]).

%% register user
handle(Params) ->
	{ok,Im} = application:get_env(ham_server,emqttd),
  	Send = get_value(<<"send_uid">>,Params),
	MsgType = get_value(<<"msg_type">>,Params),
	Content = get_value(<<"content">>,Params),
	PacketId = 
		case gen_server2:call(package_ets,{find,Send}) of 
			[] ->	
				gen_server2:cast(package_ets,{insert,Send,1}),
				1;
			[Value|_] when Value >= 65535 ->
				Value1 = 1,
				gen_server2:cast(package_ets,{delete,Send}),
				gen_server2:cast(package_ets,{insert,Send,Value1}),
				Value1;
			[Value|_] ->
				Value1 = Value + 1,
				gen_server2:cast(package_ets,{delete,Send}),
				gen_server2:cast(package_ets,{insert,Send,Value1}),
				Value1
		end,
	case MsgType of 
		3 ->
			GroupId = get_value(<<"group_id">>,Params),
			cast_svc:cast(Im, emqttd_ham, to_group_ham, [Send, GroupId, PacketId, base64:decode(Content)]);
		_ ->	
			Accept_uid = get_value(<<"accept_uid">>,Params),
			cast_svc:cast(Im, emqttd_ham, to_msg_ham, [Send, Accept_uid, PacketId, MsgType, base64:decode(Content)])
	end,						
	{ok, [{<<"code">>,0}]}.
